package com.py.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.param.InvestmentParamDto;
import com.py.payment.dto.ret.InvestmentRetDto;
import com.py.payment.entity.PyInvestment;
import com.py.payment.entity.PyUnit;
import com.py.payment.mapper.PyInvestmentMapper;
import com.py.payment.service.PyInvestmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.payment.service.PyUnitService;
import com.py.payment.tools.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 投资信息表 服务实现类
 * </p>
 *
 * @author py
 * @since 2024-04-23
 */
@Service
public class PyInvestmentServiceImpl extends ServiceImpl<PyInvestmentMapper, PyInvestment> implements PyInvestmentService {

    @Autowired
    private PyUnitService unitService;

    @Override
    public List<InvestmentRetDto> getInvestment() {
        QueryWrapper<PyInvestment> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("year");
        queryWrapper.orderByDesc("year");
        queryWrapper.last("limit 2");
        List<Integer> yearList = new ArrayList<>();
        List<PyInvestment> investments = this.list(queryWrapper);
        investments.stream().map(PyInvestment::getYear).forEach(yearList::add);

        QueryWrapper<PyUnit> unitQueryWrapper = new QueryWrapper<>();
        List<PyUnit> unitList = this.unitService.list(unitQueryWrapper);

        List<InvestmentRetDto> investmentRetDtoList = new ArrayList<>();
        unitList.forEach(item->{
            List<PyInvestment> investmentList = new ArrayList<>();
            yearList.forEach(i->{
                InvestmentParamDto paramDto = new InvestmentParamDto();
                paramDto.setYear(i);
                paramDto.setUnitId(item.getId());
                PyInvestment investment = this.baseMapper.getInvestment(paramDto);
                if(ToolsUtils.isEmpty(investment)){
                    investment = new PyInvestment();
                    investment.setUnitId(item.getId());
                    investment.setYear(i);
                    investment.setAmount("0");
                }
                investmentList.add(investment);
            });

            InvestmentRetDto retDto = new InvestmentRetDto();
            retDto.setUnitName(item.getTitle());
            retDto.setInvestmentList(investmentList);
            investmentRetDtoList.add(retDto);
        });
        return investmentRetDtoList;
    }
}
